﻿using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using FlitBit.Core;
using FlitBit.Represent;
using FlitBit.Represent.Json;

namespace FlitBit.Dto.Mvc.WebApi
{
	public class WebApiDtoModelBinder : IModelBinder
	{
		#region IModelBinder Members

		public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
		{
			var json = actionContext.Request.Content.ReadAsStringAsync()
															.Result;

			var currentFactory = FactoryProvider.Factory;
			var modelType = bindingContext.ModelType;
			var representationType = typeof(IJsonRepresentation<>).MakeGenericType(modelType);

			if (currentFactory.CanConstruct(modelType) &&
				currentFactory.CanConstruct(representationType))
			{
				var rep = (IRepresentation<string>) currentFactory.CreateInstance(representationType);
				bindingContext.Model = rep.UntypedRestoreItem(json);
				return true;
			}
			return false;
		}

		#endregion
	}
}